﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using OnlineVideos.Common;
using Common.Library;
using OnlineVideos.View_Models;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using Microsoft.Phone.Shell;
using OnlineVideos.UI;
using System.Windows.Navigation;
//using MyToolkit.Multimedia;
using OnlineVideos.Data;
//using OnlineVideos.ViewModels;
using Common.Utilities;
using System.Windows.Controls.Primitives;
using OnlineVideos.Entities;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.Storage;
using Windows.Storage.Streams;
using FlurryWP8SDK.Models;
using OnlineMovies.Views;
namespace OnlineVideos
{
    public partial class ShowVideos : UserControl
    {
       OnlineVideos.View_Models.ShowDetail detailModel;
       ObservableCollection<ShowLinks> objSongList = null;
        private bool IsDataLoaded;

        public ShowVideos()
        {
            InitializeComponent();
            IsDataLoaded = false;
            detailModel = new OnlineVideos.View_Models.ShowDetail();
            objSongList = new ObservableCollection<ShowLinks>();
            //AppState.searchtitle = string.Empty;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
               
                if (IsDataLoaded == false)
                {
                    MyProgressBar1.IsIndeterminate = true;
                    GetPageDataInBackground();
                    IsDataLoaded = true;

                }
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in UserControl_Loaded Method In ShowVideos.cs file.", ex);
            }
        }

        private void GetPageDataInBackground()
        {
            BackgroundHelper bwHelper = new BackgroundHelper();

            bwHelper.AddBackgroundTask(
                                        (object s, DoWorkEventArgs a) =>
                                        {
                                            a.Result = OnlineShow.GetShowLinksByType(AppSettings.ShowID, LinkType.Songs/*, false*/);
                                        },
                                        (object s, RunWorkerCompletedEventArgs a) =>
                                        {
                                            objSongList = (ObservableCollection<ShowLinks>)a.Result;
                                            if (objSongList.Count > 0)
                                            {
                                                lbxSongsList.ItemsSource = objSongList;
                                                tblkFavNoSongs.Visibility = Visibility.Collapsed;
                                              
                                                lbxSongsList.Loaded += new RoutedEventHandler(lbxSongsList_Loaded);
                                              
                                            }
                                            else
                                            {
                                                if (ResourceHelper.ProjectName == AppResources.VideoMix)
                                                {
                                                    Constants.VisiablehelpImage = true;
                                                     tblkFavNoSongs.Visibility = Visibility.Visible;
                                                     tblkFavNoSongsForVideoMix.Visibility = Visibility.Visible;
                                                     tblkFavNoSongs.Text = "Please add some videos to the mix ";
                                                     tblkFavNoSongsForVideoMix.Text = "and create bookmarks in each video.";
                                                }
                                                else
                                                {
                                                    lbxSongsList.ItemsSource = null;
                                                    tblkFavNoSongs.Visibility = Visibility.Visible;
                                                    tblkFavNoSongs.Text = "No " + AppResources.ShowDetailPageSongsPivotTitle as string + " available";
                                                }
                                            }
                                            MyProgressBar1.IsIndeterminate = false;
                                        }
                                      );

            bwHelper.RunBackgroundWorkers();
          
        }

        void lbxSongsList_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                lbxSongsList.IsEnabled = true;
                if (PhoneApplicationService.Current.State.Keys.Contains("searchtitle"))
                {
                    PageHelper.SetSelectedItemForegroundColor(this.lbxSongsList, AppState.searchtitle);

                }
                else
                {
                    PageHelper.SetSelectedItemForegroundColor(this.lbxSongsList, "");
                }
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in lbxSongsList_Loaded Method In ShowVideos.cs file.", ex);
            }
        }

       

        private void btnFavSong_Click(object sender, RoutedEventArgs e)
        {

            
            try
            {
                detailModel.AddToFavorites(lbxSongsList, sender as MenuItem, LinkType.Songs);

            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in btnFavSong_Click Method In ShowVideos.cs file.", ex);
            }
        }
        //public bool checklink(string linktype)
        //{
        //    bool exists = false;
        //    try
        //    {
        //        if (Task.Run(async () => await Storage.FavouriteFileExists("Favourites.xml")).Result)
        //        {
        //            int sid = int.Parse(AppSettings.ShowID);
        //            XDocument xdoc = new XDocument();
        //            StorageFolder store = ApplicationData.Current.LocalFolder;

        //            StorageFolder file = Task.Run(async () => await store.CreateFolderAsync("Favourites", Windows.Storage.CreationCollisionOption.OpenIfExists)).Result;
        //            StorageFile file1 = Task.Run(async () => await file.CreateFileAsync("Favourites.xml", Windows.Storage.CreationCollisionOption.OpenIfExists)).Result;
        //            var f = Task.Run(async () => await file1.OpenAsync(FileAccessMode.Read)).Result;
        //            IInputStream inputStream = f.GetInputStreamAt(0);
        //            DataReader dataReader = new DataReader(inputStream);
        //            uint numBytesLoaded = Task.Run(async () => await dataReader.LoadAsync((uint)f.Size)).Result;
        //            string xmlData = (dataReader.ReadString(numBytesLoaded)).ToString();
        //            System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlData));
        //            xdoc = XDocument.Load(ms);
        //            dataReader.DetachStream();
        //            inputStream.Dispose();
        //            f.Dispose();
        //            ms.Dispose();



        //            var data = xdoc.Root.Elements("Show").Where(i => i.Attribute("id").Value == AppSettings.ShowID.ToString()).Elements().Where(i=>i.Name==linktype && i.Attribute("no").Value==)
        //            if (data.Count() > 0)
        //            {
        //                if (data[0].Value == "1")
        //                    exists = true;

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Exceptions.SaveOrSendExceptions("Exception in Checklink  Method In Detailpage", ex);
        //    }
        //    return exists;

        //}
        private void btnBrokenSong_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                detailModel.ReportBrokenLink(lbxSongsList, sender as MenuItem);
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in btnBrokenSong_Click Method In ShowVideos.cs file.", ex);
            }
        }

        private void sharelink_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                detailModel.PostAppLinkToSocialNetworks(lbxSongsList, sender as MenuItem, " Watch Bollywood Song ");
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in sharelink_Click Method In ShowVideos.cs file.", ex);
            }
        }

        private void ratelink_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                detailModel.RateThisLink(lbxSongsList, sender as MenuItem, "Details");
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in ratelink_Click Method In ShowVideos.cs file.", ex);
            }
        }

        private  void lbxSongsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxSongsList.SelectedIndex == -1)
                return;
            AppSettings.LinkTitle = (lbxSongsList.SelectedItem as ShowLinks).Title.ToString();
            AppSettings.LinkType = (lbxSongsList.SelectedItem as ShowLinks).LinkType.ToString();
          
            var selecteditem1 = (sender as Selector).SelectedItem as ShowLinks;
            var Itemcollection = (sender as ListBox).Items.ToList();
            Constants.YoutubePlayList = new Dictionary<string, string>();
            foreach (var item in Itemcollection.Cast<ShowLinks>().Where(i => i.LinkOrder > selecteditem1.LinkOrder))
            {
                if(!Constants.YoutubePlayList.ContainsKey(item.LinkUrl))
                Constants.YoutubePlayList.Add(item.LinkUrl, item.Title);
            }
            foreach (var item in Itemcollection.Cast<ShowLinks>().Where(i => i.LinkOrder < selecteditem1.LinkOrder))
            {
                if (!Constants.YoutubePlayList.ContainsKey(item.LinkUrl))
                Constants.YoutubePlayList.Add(item.LinkUrl, item.Title);
            }
            AppSettings.PlayVideoTitle = Constants.YoutubePlayList.FirstOrDefault().Value;
           History objHistory = new History();
           objHistory.SaveSongHistory((lbxSongsList.SelectedItem as ShowLinks).ShowID.ToString(), (lbxSongsList.SelectedItem as ShowLinks).Title);
       
           if (ResourceHelper.AppName == Apps.Indian_Cinema_Pro.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Story_Time_Pro.ToString())
               AppSettings.startplayingforpro = true;
            else
               AppSettings.startplaying = true;
         if (ResourceHelper.ProjectName == AppResources.VideoMix)
         {
             var item = lbxSongsList.SelectedItem as ShowLinks;
             AppSettings.ShowID = item.ShowID.ToString();
             AppSettings.LinkUrl = item.LinkUrl;
             AppSettings.Title = item.Title;
             Constants.TileImageUrl = item.UrlType;
             AppSettings.LinkOrder =item.LinkOrder.ToString();
             PageHelper.NavigateTo(NavigationHelper.MixVideosPopupPage);
         }
         else
         {
             //YoutubeApi.Youtube.PlayYoutubeVideo((lbxSongsList.SelectedItem as ShowLinks).LinkUrl);
             PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
             Page p = frame.Content as Page;
             p.NavigationService.Navigate(new Uri("/Views/Youtube.xaml?myid=" + (lbxSongsList.SelectedItem as ShowLinks).LinkUrl, UriKind.Relative));
             //PageHelper.NavigateTo("Youtube", AppSettings.LinkUrl);
             //MyToolkit.Multimedia.YouTube.LoadYoutubeVideo((lbxSongsList.SelectedItem as ShowLinks).LinkUrl);
         }
        
            lbxSongsList.SelectedIndex = -1;
            lbxSongsList.IsEnabled = false;
            lbxSongsList.ItemsSource = OnlineShow.GetShowLinksByType(AppSettings.ShowID, LinkType.Songs/*, false*/);
        }
       
       
        private void btnpintostart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string showLinkTitle;
                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                Page p = frame.Content as Page;
                Pivot p1 = (Pivot)(p.FindName("pvtMainDetails"));
                if (p1 != null)
                    Constants.topsongnavigation = p1.SelectedIndex.ToString();
                ListBoxItem selectedListBoxItem = this.lbxSongsList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
                if (selectedListBoxItem == null)
                    return;
                showLinkTitle = (selectedListBoxItem.Content as ShowLinks).Title;
                AppSettings.ShowLinkTitle = AppSettings.ShowID + (selectedListBoxItem.Content as ShowLinks).Title;
                ShellTileHelper.PinVideoLinkToStartScreen(AppSettings.ShowID, selectedListBoxItem.Content as ShowLinks);
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in btnpintostart_Click Method In ShowVideos.cs file.", ex);
            }

        }

        private void ContextMenu_Opened(object sender, RoutedEventArgs e)
        {


            try
            {
                ContextMenu mainmenu = sender as ContextMenu;
                foreach (MenuItem contextMenuItem in mainmenu.Items)
                {
                    ListBoxItem selectedListBoxItem = this.lbxSongsList.ItemContainerGenerator.ContainerFromItem((sender as ContextMenu).DataContext) as ListBoxItem;
                    if (selectedListBoxItem == null)
                        return;
                    if (contextMenuItem.Name == "Pin")
                    {
                        if (ShellTileHelper.IsPinned(AppSettings.ShowID + (selectedListBoxItem.Content as ShowLinks).Title))
                        {
                            contextMenuItem.Header = Constants.UnpinFromStartScreen;
                        }
                        else
                        {
                            contextMenuItem.Header = Constants.PinToStartScreen;
                        }
                    }
                    if (contextMenuItem.Name == "Rating")
                    {
                        contextMenuItem.Header = AppResources.AllowRatingLinkContextMenuLabel;
                    }
                    if (contextMenuItem.Name.Contains("favorites"))
                    {
                        int showid1 = Convert.ToInt32(AppSettings.ShowID);
                        int linkid = (selectedListBoxItem.Content as ShowLinks).LinkID;
                        string linktype = (selectedListBoxItem.Content as ShowLinks).LinkType;
                        if (Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == showid1 && i.LinkID == linkid && i.LinkType == linktype).FirstOrDefaultAsync()).Result != null)
                        {
                            if (Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(i => i.ShowID == showid1 && i.LinkID == linkid && i.LinkType == linktype).FirstOrDefaultAsync()).Result.IsFavourite == false)
                            {
                                contextMenuItem.Header = "add to favorites";
                            }
                            else
                                contextMenuItem.Header = "remove from favorites";
                        }
                    }

                }
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                int showid = AppSettings.ShowUniqueID;
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null || ResourceHelper.AppName == Apps.Video_Mix.ToString())
                {

                    var item = mainmenu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                    item.IsEnabled = true;
                }
                else
                {
                    var item = mainmenu.Items.OfType<MenuItem>().First(m => (string)m.Name == "del");
                    item.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened Method In ShowVideos.cs file.", ex);
            }
        }

        private async void del_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem menu = sender as MenuItem;
                ListBoxItem selectedListBoxItem = lbxSongsList.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                int showid = (selectedListBoxItem.Content as ShowLinks).ShowID;
                int linkid = (selectedListBoxItem.Content as ShowLinks).LinkID;
                string linktype = (selectedListBoxItem.Content as ShowLinks).LinkType;
                var xquery = Task.Run(async () => await Constants.connection.Table<ShowLinks>().Where(id => id.ShowID == showid && id.LinkID == linkid && id.LinkType == linktype).FirstOrDefaultAsync()).Result;
                if (xquery != null)
                {
                    if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null || ResourceHelper.AppName == Apps.Video_Mix.ToString())
                    {
                        await Constants.connection.DeleteAsync(xquery);
                    }
                }
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in del_Click_1 Method In ShowVideos.cs file.", ex);
            }
        }

    }
}